<?php
/**
 * Base Controller for common oauth logic
 *
 * @author brian
 */
abstract class Social_Oauth_BaseController extends Zend_Controller_Action {
	/**
	 * @var String
	 */
	protected $serviceKey;
	/**
	 * @var Zend_Session_Namespace
	 */
	protected $session;
	/**
	 * @var Zend_Config_Ini 
	 */
	protected $config;
	/**
	 * @var Zend_Filter_Input 
	 */
	protected $params;
	
	/**
	 * Initialization 
	 */
	public function init()
	{
		if ( empty($this->serviceKey))
		{
			throw new Exception('Oauth Service Key not found');
		}
		$this->session = new Zend_Session_Namespace($this->serviceKey);
		$this->config = Zend_Registry::get('api_keys')->{$this->serviceKey};
		
		$this->_helper->viewRenderer->setNoRender();
		$this->params = new Zend_Filter_Input(null, null, $this->_request->getParams());
	}
	
	/**
	 * Start Google authentication 
	 */
	public function startauth( $scope=null )
	{
		$config = $this->config->oauth->params->toArray();
		$consumer = new Zend_Oauth_Consumer($config);

		// fetch a request token
		$token = $consumer->getRequestToken($scope);

		// persist the token to storage
		$this->session->request_token = serialize($token);

		// redirect the user
		$consumer->redirect();
	}
	
	/**
	 * Complete Netflix authentication
	 */
	public function finishauth()
	{
		$config = $this->config->oauth->params->toArray();
		$consumer = new Zend_Oauth_Consumer($config);

		if (!empty($_GET) && isset($this->session->request_token))
		{
			$token = $consumer->getAccessToken( $_GET, unserialize($this->session->request_token));
			$this->session->token = serialize($token);

			// Now that we have an Access Token, we can discard the Request Token
			$this->session->request_token = null;
		}
		else
		{
			// Something went horribly wrong
			exit('Invalid callback request. Cannot continue.');
		}
	}
	
	/**
	 * Cancel Authentication 
	 */
	public function cancelauthAction()
	{
		// TODO
	}
	
	/**
	 * Helper method for determining authentication status
	 * @return bool 
	 */
	protected function isAuthenticated()
	{
		return !(empty($this->session->token));
	}
	
}

?>
